package org.jeecg.modules.front.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.front.constant.ResultBaseCodeEnum;
import org.jeecg.modules.front.entity.BusUser;
import org.jeecg.modules.front.entity.BusUserDetail;
import org.jeecg.modules.front.entity.req.WxUserRegisterReq;
import org.jeecg.modules.front.entity.resp.BusUserResp;
import org.jeecg.modules.front.mapper.BusUserDetailMapper;
import org.jeecg.modules.front.mapper.BusUserMapper;
import org.jeecg.modules.front.service.BusUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class BusUserServiceImpl extends ServiceImpl<BusUserMapper, BusUser> implements BusUserService {
    @Value("${wx.miniapp.appId}")
    private String appId;

    @Value("${wx.miniapp.secret}")
    private String secret;

    @Autowired
    private BusUserDetailMapper busUserDetailMapper;



    @Override
    public BusUserResp getByUserId(String id) {
        return baseMapper.getByUserId(id);
    }

    @Override
    public Result<BusUserResp> wxAppUserLogin(WxUserRegisterReq req) {
        {
            //解析code及密文
            // 配置微信小程序账号配置
            Result result = new Result();
            WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
            if(StringUtils.isBlank(appId)){
                log.error("微信小程序appId未配置或配置有误!", JSON.toJSONString(appId));
                result.setMessage("登录失败!");
                result.setSuccess(false);
                return result;
            }
            wxMaDefaultConfig.setAppid(appId);
            //获取appSecret
            if(StringUtils.isBlank(secret)){
                log.error("微信小程序appSecret未配置或配置有误!", JSON.toJSONString(secret));
                result.setMessage("登录失败!");
                result.setSuccess(false);
                return result;
            }
            wxMaDefaultConfig.setSecret(secret);
            WxMaService wxMaService = new WxMaServiceImpl();
            wxMaService.setWxMaConfig(wxMaDefaultConfig);
            // 获取用户登录session openid信息
            WxMaJscode2SessionResult sessionInfo = null;
            try {
                //使用了微信公众平台提供的wxMaService和getUserService接口来获取用户的sessionInfo信息。
                sessionInfo = wxMaService.getUserService().getSessionInfo(req.getCode());
            } catch (WxErrorException e) {
                e.printStackTrace();
                result.setCode(Integer.parseInt(ResultBaseCodeEnum.WX_MINIAPP_GET_USER_SESSION_ERROR.getCode()));
                result.setMessage("登录失败!");
                result.setSuccess(false);
                return result;
            }
            //判断sessioninfo是否为空
            if(sessionInfo == null){
                result.setCode(Integer.parseInt(ResultBaseCodeEnum.WX_MINIAPP_GET_USER_SESSION_NULL_ERROR.getCode()));
                result.setMessage("登录失败!");
                result.setSuccess(false);
                return result;
            }
            // 查找授权表，看是否有相关授权信息
            String openId = sessionInfo.getOpenid();

            // 获取请求中的电话号码
            String phoneNumberStr = req.getPhoneNumber();
            log.info("获取请求中的电话号码:{}", phoneNumberStr);
            if(StringUtils.isEmpty(phoneNumberStr) || phoneNumberStr.length() < 11){
                result.setCode(Integer.parseInt(ResultBaseCodeEnum.WX_MINIAPP_REQ_PHONE_NUMBER_ERROR.getCode()));
                result.setMessage("登录失败!");
                result.setSuccess(false);
                return result;
            }
            String phoneNumber;
//        WxMaUserInfo userInfo = null;
            // 解析用户手机号
            if (phoneNumberStr.length() > 11) {
                log.info("手机号为密文，进行解密操作");
                if(StringUtils.isEmpty(req.getIv())){
                    result.setCode(Integer.parseInt(ResultBaseCodeEnum.WX_MINIAPP_IV_NULL_ERROR.getCode()));
                    result.setMessage("登录失败!");
                    result.setSuccess(false);
                    return result;
                }
                WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService()
                        .getPhoneNoInfo(sessionInfo.getSessionKey(), phoneNumberStr, req.getIv());
//            userInfo = wxMaService.getUserService()
//                    .getUserInfo(sessionInfo.getSessionKey(), userInfoStr, req.getUserInfoIv());
                phoneNumber = phoneNoInfo.getPhoneNumber();
                log.info("密文解析出的手机号码：phoneNumber={}", JSON.toJSONString(phoneNumber));
            } else {
                log.info("手机号为密文，未进行解密操作");
                phoneNumber = phoneNumberStr;
            }
            //判断userInfo是否为空
//        if(userInfo == null){
//            return ResultDataVO.error(ResultBaseCodeEnum.WX_MINIAPP_GET_USER_INFO_NULL_ERROR.getCode(),"登录失败！");
//        }
//        String unionid = userInfo.getUnionId();
            //判断是否有当前手机号码用户
            BusUserResp byPhone = this.getUserByPhone(phoneNumber);
            if(byPhone != null){
                if(StringUtils.isNotBlank(byPhone.getOpenId())){
                    result.setResult(byPhone);
                    result.setSuccess(true);
                    return result;
                }
                BusUser busUser = new BusUser();
                BeanUtils.copyProperties(byPhone, busUser);
                busUser.setOpenId(openId);
                busUser.setUpdateTime(new Date());
                baseMapper.updateById(busUser);
                byPhone.setOpenId(openId);
                result.setResult(byPhone);
                result.setSuccess(true);
                return result;
            }
            //不存在的时候创建用户
            BusUser registerReq = new BusUser();
            registerReq.setPhoneNum(phoneNumber);
            registerReq.setOpenId(openId);
            baseMapper.insert(registerReq);
            if(registerReq != null){
                BusUserResp userInfoResp = new BusUserResp();
                BeanUtils.copyProperties(registerReq, userInfoResp);
                result.setResult(userInfoResp);
                result.setSuccess(true);
                return result;
            }
            result.setMessage("openId无效，获取失败");
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public BusUserResp getUserByPhone(String phoneNum) {
        BusUser busUser = baseMapper.selectOne(new LambdaQueryWrapper<BusUser>().eq(BusUser::getPhoneNum, phoneNum));
        BusUserDetail busUserDetail = busUserDetailMapper.selectOne(new LambdaQueryWrapper<BusUserDetail>().eq(BusUserDetail::getPhoneNum, phoneNum));
        BusUserResp resp = null;
        if (busUser != null) {
            resp = new BusUserResp();
            BeanUtils.copyProperties(busUser, resp);
            if (busUserDetail != null) {
                BeanUtils.copyProperties(busUserDetail, resp);
            }
        }
        return resp;
    }
}
